package com.midian.common.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.midian.action.mc.common.AjaxAction;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

/**
 * 
 * @Title:TODO  
 * @Desription:
 * 系统数据合法验证拦截器，如系统数据合法验证不通过，默认输出数据非法
 * 服务器端验证一般是用来防止用户通过非常规手段跳过客户端验证，输入非法数据，导致
 * 系统数据异常，开发时应做好客户端验证。不能依赖于服务器验证。
 * @Company:MDKG
 * @ClassName:QaraSysValidationInterceptor.java
 * @Author:zhucong
 * @CreateDate:2013-6-7 下午6:12:18  
 * @UpdateUser:zhucong  
 * @Version:0.1
 */
public class SysValidationInterceptor extends MethodFilterInterceptor{
	
	private static final long serialVersionUID = -4079811345105033741L;
	private static final Logger LOG = LoggerFactory.getLogger(SysValidationInterceptor.class);  
    private static final String DEFAULT_ENCODING = "UTF-8";
    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
    	//System.out.println("ajaxjsonInterceptor");
        HttpServletResponse response = ServletActionContext.getResponse();
        HttpServletRequest request = ServletActionContext.getRequest();
        Object action = invocation.getAction(); 
        //如果action实现了验证接口并且继承了AjaxAction类才做处理
        if (action instanceof ValidationAware&&action instanceof AjaxAction) {
            ValidationAware validationAware = (ValidationAware) action;
            if (validationAware.hasErrors()) {
            	log.error("服务器验证 失败:"+validationAware.getFieldErrors().toString());
                return generateJSON(request, response, validationAware);
            }
        }
         return invocation.invoke();
        
    }

    private String generateJSON(HttpServletRequest request, HttpServletResponse response, ValidationAware validationAware)
            throws IOException {
    	response.setCharacterEncoding(DEFAULT_ENCODING);
    	response.setContentType("text/html;charset=UTF-8");
    	PrintWriter out = response.getWriter();
        out.print(buildResponse(validationAware));
        out.flush();
        out.close();
        return Action.NONE;
    }
  
    @SuppressWarnings("unchecked")
    protected String buildResponse(ValidationAware validationAware) {
    	Collection<String> actionErrors = validationAware.getActionErrors();
    	String errMsg = "";
    	for (String tempErrMsg : actionErrors) {
    		if(tempErrMsg.indexOf("the request was rejected because its size") != -1) {
    			errMsg = "您上传的文件过大，请重新上传！";
    			break;
    		}
		}
    	StringBuilder sb = new StringBuilder();
        sb.append("<script type=\"text/javascript\">");
        sb.append("window.parent.sysErrorShow('"+errMsg+"'); ");
        sb.append("</script>");
        return sb.toString();
    }
}
